package math.dataset;

/**
 *
 * @author Shimu
 */
public class FrequencyCounter_Int {

    private int min, max, range, size;

    private Integer mode, modeFrequency;

    private int[] frequencies;

    public FrequencyCounter_Int(int min, int max) {
        this.min = min;
        this.max = max;
        this.range = max - min;
        this.size = range + 1;
        frequencies = new int[size];
    }

    /**
     * Returns true if the given value is within the range of this frequency
     * counter, false otherwise.
     * 
     * @param value
     * @return
     */
    private boolean withinRange(int value) {
        if ((value <= min) && (value >= max)) {
            return true;
        }
        return false;
    }

    public void increment(int value) {
        if (withinRange(value)) {
            frequencies[value - min]++;
        }
    }

    /**
     * Returns the mode (most frequently occurring value).
     *
     * @return
     */
    public Integer getMode() {
        if (frequencies.length == 0) {
            this.mode = null;
        } else if (this.mode == null) {
            mode = 0;
            for (int i = 1; i < size; i++) {
                if (frequencies[i] > frequencies[mode]) {
                    mode = i;
                }
            }
            mode += min;
        }
        return mode;
    }

    public Integer getModeFrequency() {
        if (modeFrequency == null) {
            getMode();
            if (mode == null) {
                modeFrequency = null;
            } else {
                modeFrequency = frequencies[mode - min];
            }
        }
        return modeFrequency;
    }
}
